package com.surprise.es;

import javax.annotation.PostConstruct;

import org.apache.commons.lang.StringUtils;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.surprise.base.util.ListUtils;




/**
 * ESFactory.java
 * @author nick
 * 2015年3月9日
 */
@Component
public class ESFactory {
    @Autowired
    private ESConfig config;
    
    private String[] hosts;
    private Integer[] ports;
    
    @PostConstruct
    public void init() {
        hosts = StringUtils.split(config.getHosts(), ',');
        ports = ListUtils.convert(Lists.newArrayList(StringUtils.split(config.getPorts(), ',')), Integer.class).toArray(new Integer[0]);        
    }
    
    public Client client() {
        Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", config.getClusterName()).build();
        TransportClient client = new TransportClient(settings);
        for(int i=0;i<hosts.length;i++) {
            client.addTransportAddress(new InetSocketTransportAddress(hosts[i], ports[i]));
        }
        return client;
    }
    
    public void returnResource(Client client) {
        if(client != null) {
            client.close();
        }
    }
}
